<?php
namespace app\home\controller;

use app\common\model\User as UserModel;
use app\common\controller\HomeBase;
use think\Db;
use think\Config;


/**
 * 短信验证码
 * Class news
 */
class MobileCode extends HomeBase
{
    /**
     *
     * 发送短信验证码
     * @param int    $code 验证码
     * @param int    $mobile 手机号
     * @return mixed
     */
    public function send_code($code,$mobile){
        if(empty($mobile)){
            echo json_encode('请输入手机');exit();
        }
        $mobilepreg='/^1[3|4|5|7|8][0-9]{9}$/';
        if (!preg_match($mobilepreg,$mobile)) {
            show(0,'手机不符合规范');
            exit();
        }
        if (!$this->checkLimit($mobile)) {
            show(0,'发送超过限制稍后再试！');
        }
        header('content-type:text/html;charset=utf-8');

        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL

        $smsConf = array(
                //'key'   => '7057687f0acc8b6ec93e9fdf22f6a615', //您申请的APPKEY old
                'key'   => '159d37157d939793a2372f85b1e5b53f', //您申请的APPKEY new
                'mobile'    => $mobile, //接受短信的用户手机号码
                //'tpl_id'    => '79318', //您申请的短信模板ID，根据实际情况修改 old
                'tpl_id'    => '81538', //您申请的短信模板ID，根据实际情况修改 new
                'tpl_value' =>'#code#='.$code.'&#company#=淘享富' //您设置的模板变量，根据实际情况修改
        );
        // 短信发送成功写入数据库
        /*$sms_log['mobile'] = $mobile;
        $sms_log['ip'] = $_SERVER["REMOTE_ADDR"];//ip;
        $sms_log['time'] = time();
        model('sms_log')->save($sms_log);
        show(1,"发送的验证码是：".$code);*/
        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信

        if($content){
            //show(0,"发送的验证码是：".$code);
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                // 短信发送成功写入数据库
                $sms_log['mobile'] = $mobile;
                $sms_log['ip'] = $_SERVER["REMOTE_ADDR"];//ip;
                $sms_log['time'] = time();
                model('sms_log')->save($sms_log);
                show(1,'短信发送成功');
                
            }else{
                //状态非0，说明失败
                $msg = $result['reason'];
                show(0,"短信发送失败(".$error_code.")：".$msg);
                //echo json_encode("短信发送失败(".$error_code.")：".$msg);exit();
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
            //echo json_encode("请求发送短信失败");
            show(0,'请求发送短信失败');

        }
    }
    Public function checkLimit($mobile){
        $ip=$_SERVER["REMOTE_ADDR"];//ip
        // 昨天时间戳范围
        $begin_today = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end_today   = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $ip_num = model("sms_log")->where("ip = '".$ip."' and time > '".$begin_today."' and time < '".$end_today."'")->count();
        $mobile_num = model("sms_log")->where("mobile = '".$mobile."' and time > '".$begin_today."' and time < '".$end_today."'")->count();
        $before_time = time()-60;
        $now_num = model("sms_log")->where("mobile = '".$mobile."' and time > '".$before_time."' and time < '".time()."'")->count();
        if ($ip_num > 100 || $mobile_num > 100 || $now_num) {
            return false;
        }else{
            return true;
        }
    }

    /**
     * 获取注册验证码
     * @return mixed
     */
    public function getRegMobileCode()
    {
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 验证规则
            $validate = validate('GetChangeMobileCode');   
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{
                // 发送验证码
                $code = rand(1111,9999);
                //$code = '1234';
                session('reg_code',$code);
                session('reg_mobile',$data['mobile']);
                $this->send_code($code,$data['mobile']);
            }
        }
    }
    /**
     * 获取忘记密码的验证码
     * @return mixed
     */
    public function getForgetMobileCode()
    {
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 验证规则
            $validate = validate('GetForgetMobileCode');   
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{
                // 发送验证码
                $code = rand(1111,9999);
                //$code = '1234';
                session('forget_code',$code);
                session('forget_mobile',$data['mobile']);
                $this->send_code($code,$data['mobile']);
            }
        }
    }
    /**
     * 获取验证码 更换手机号
     * @return mixed
     */
    public function getChangeMobileCode()
    {
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 验证规则
            $validate = validate('GetChangeMobileCode');   
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{
                // 发送验证码
                $code = rand(1111,9999);
                //$code = '1234';
                session('change_code',$code);
                session('change_mobile',$data['mobile']);
                // 发送短信
                $this->send_code($code,$data['mobile']);
            }
        }
    }
    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

}

?>
